package com.zisuyi.uilibrary.view

import android.content.Context
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.TextView
import com.weilele.mvvm.widget.BaseTextView
import com.zisuyi.uilibrary.R
import com.zisuyi.uilibrary.uitils.SoundUtils


/**
 * 若红楼梦空，亦初心不变
 * 作者：weijiale
 * 包名：com.real.money.easy.customview
 * 时间：2018/8/1 15:26
 * 描述：支持设置字体的textView
 */
open class FontTextView : BaseTextView, IClickScale {
    companion object {
        @JvmField
        var fontTypeface = mutableMapOf<String, Typeface>()
        fun TextView.setFont(fontPathName: String?) {
            if (fontPathName == null) {
                if (typeface.isBold) {
//                    setFont("font/Floane-Bold-2.otf")
                    setFont("font/CarterOne.ttf")
                } else {
//                    setFont("font/Floane-Bold-2.otf")
                    setFont("font/CarterOne.ttf")
                }
                return
            }
            try {
                if (fontTypeface[fontPathName] == null) {
                    fontTypeface[fontPathName] =
                        Typeface.createFromAsset(context.assets, fontPathName)
                }
                typeface = fontTypeface[fontPathName]
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }


    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        initView(context, attrs, defStyleAttr)
    }

    private fun initView(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) {
        val attributes = context?.obtainStyledAttributes(attrs, R.styleable.FontTextView)
        val fontPath = attributes?.getString(R.styleable.FontTextView_fontAssetsPath)
        setFont(fontPath)
        attributes?.recycle()
    }


    override fun onTouchEvent(event: MotionEvent?): Boolean {
        onTouchEventHelper(this, event)
        return super.onTouchEvent(event)
    }

    override fun setOnClickListener(l: OnClickListener?) {
        super.setOnClickListener {
            SoundUtils.play(SoundUtils.GameMusic.DoubleCoin.bean)
            l?.onClick(it)
        }
    }
}